const router = require('express').Router()
const auth = require('./auth')

// Preload user profile on routes with ':username'
router.param('username', function(req, res, next, username) {
  req.app.get('sequelize').models.User.findOne({ where: { username: username } })
    .then(function(user) {
      if (!user) {
        return res.sendStatus(404)
      }

      req.profile = user

      return next()
    })
    .catch(next)
})

router.get('/:username', auth.optional, function(req, res, next) {
  if (req.payload) {
    req.app.get('sequelize').models.User.findByPk(req.payload.id).then(function(user) {
      if (!user) {
        return res.json({ profile: req.profile.toProfileJSONFor(false) })
      }

      return res.json({ profile: req.profile.toProfileJSONFor(user) })
    })
  } else {
    return res.json({ profile: req.profile.toProfileJSONFor(false) })
  }
})

router.post('/:username/follow', auth.required, function(req, res, next) {
  let profileId = req.profile.id

  req.app.get('sequelize').models.User.findByPk(req.payload.id)
    .then(function(user) {
      if (!user) {
        return res.sendStatus(401)
      }

      return user.follow(profileId).then(function() {
        return res.json({ profile: req.profile.toProfileJSONFor(user) })
      })
    })
    .catch(next)
})

router.delete('/:username/follow', auth.required, function(req, res, next) {
  let profileId = req.profile.id

  req.app.get('sequelize').models.User.findByPk(req.payload.id)
    .then(function(user) {
      if (!user) {
        return res.sendStatus(401)
      }

      return user.unfollow(profileId).then(function() {
        return res.json({ profile: req.profile.toProfileJSONFor(user) })
      })
    })
    .catch(next)
})

module.exports = router
